<template>
  <div class="monitor">
    <!-- 搜索部分 -->
    <dynForm
      :info-form="searchHeaderForm"
      :search-tags="searchTags"
      :select-list="selectList"
    >
      <!-- <el-button
        type="primary"
        icon="el-icon-search"

        @click="doSearch"
      >
        {{ $t("search") }}</el-button
        > -->
    </dynForm>
    <div class="grid-content">
      <div class="grid-content-left">
        <div class="box-eqp">
          <statusList />
          <div
            :style="{'background-image': 'url(' + baseApi + '/' + layoutAttr.image + ')',}"
            class="grid-content-left-c"
          >
            <!-- 设备布局 -->
            <div
              v-for="i of layoutList"
              :key="i.eqp1Id"
              :style="{ left: i.left + 'px', top: i.top + 'px','backgroundImage':'url('+imgFilter(i.status) +')'}"
              class="equipment"
              @click="layoutInfoForm(i.eqp1Id)"
              @contextmenu.stop.prevent="$refs.ctxshow.showMenu($event,i)">
              <span>{{ i.eqp1Id }}</span>
              <span v-if="i.eqp2Id">{{ i.eqp2Id }}</span>
              <!-- 不能弄伪类 -->
              <!-- :style="{ 'borderColor': statusDisplay[i.mesEqpStatus], 'color':statusDisplay[i.mesEqpStatus] }" -->
              <div
                class="status-display"
              >{{ i.mesEqpStatus }} </div>
            </div>
            <e-vue-contextmenu
              v-show="visible"
              id="contextStyle"
              ref="ctxshow"
              @ctx-show="show"
              @ctx-hide="hide">
              <a
                v-if="eqpInfo.trackStatus===0"
                class="ctxshow-menu"
                @click="changeRouter('TrackIn',eqpInfo)">{{ $t('TrackIn') }}</a>
              <a
                v-if="eqpInfo.trackStatus===1"
                class="ctxshow-menu"
                @click="changeRouter('TrackOut',eqpInfo)">
                {{ $t('TrackOut') }}</a>
              <a
                v-if="eqpInfo.trackStatus===1"
                class="ctxshow-menu"
                @click="workRecordRouter('WorkRecord',eqpInfo)">
                {{ $t('WorkRecord') }}</a>
              <a
                v-if="eqpInfo.trackStatus===1"
                class="ctxshow-menu"
                @click="workRecordRouter('HandOver',eqpInfo)">
                {{ $t('HandOver') }}</a>
            </e-vue-contextmenu>
          </div>
        </div>
      </div>
      <div class="grid-content-right">
        <progressList :total="totalQty||0" :status-count-list="statusCountList||[]"/>
      </div>
    </div>
    <!-- 基础信息弹窗 -->
    <basicInformationForm ref="basicInformationForm" />
  </div>
</template>
<script>
import basicInformationForm from './components/basicInformationForm'
import progressList from './components/progress'
import statusList from './module/statusColor'
import eqpAreaApi from '@/api/production/eqpMonitor'
import { getLayoutsInfo } from '@/api/production/layoutDesign'
import { mapGetters } from 'vuex'

export default {
  name: 'EqpMonitor',
  components: {
    statusList,
    progressList,
    basicInformationForm
  },
  data() {
    const statusDisplay = Object.freeze({
      'RUN': '#1AD175',
      'ALARM': '#EC4014',
      'IDLE': '#3F8EDD',
      'NETWORKFAILURE': '#959595',
      'STOP': '#FFDD20'
    })
    return {
      visible: false,
      eqpTimer: null,
      layoutList: [],
      statusCountList: [],
      totalQty: '',
      byAreaList: [],
      eqpInfo: {}, // 开批结批需要
      statusDisplay: statusDisplay,
      eqpNumbers: {},
      count: 0,
      layoutAttr: {},

      searchHeaderForm: {
        areaName: '',
        layoutId: ''
      },
      searchTags: Object.freeze([
        { label: this.$t('areaName'), prop: 'areaName', tag: 'DynSelect', event: async(value) => {
          this.$set(this.searchHeaderForm, 'layoutId', '')
          const res = await eqpAreaApi.getLayoutsByArea({ areaName: value })
          if (res.data.length) {
            this.$set(this.searchHeaderForm, 'layoutId', res.data[0].id)
            this.$set(this.selectList, 'layoutId', res.data)
            this.getEqpLayout(res.data[0].id)
          } else {
            this.$set(this.searchHeaderForm, 'layoutId', '')
            this.$set(this.selectList, 'layoutId', [])
            this.layoutList = []
            this.statusCountList = []
            this.totalQty = 0
          }
        } },
        { label: this.$t('layoutName'), prop: 'layoutId', tag: 'DynSelect', event: this.getEqpLayout }
      ]),
      selectList: {}
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    this.getEqpAreasList()
    this.initEqpLayout()
    this.reacquireEqpLayout()
  },
  destroyed() {
    clearTimeout(this.eqpTimer)
  },
  methods: {
    // 轮询接口
    reacquireEqpLayout(isFirst = false) {
      clearTimeout(this.eqpTimer)
      isFirst && this.getEqpLayout(this.searchHeaderForm.layoutId)
      this.eqpTimer = setTimeout(() => {
        this.reacquireEqpLayout(true)
      }, 60000)
    },
    // 初始化 三部走
    async initEqpLayout() {
      // 1
      const res = await eqpAreaApi.initEqpLayout()
      const { areaName, layoutId } = res.data
      this.searchHeaderForm.areaName = areaName
      // 2
      const layoutList = await eqpAreaApi.getLayoutsByArea({ areaName: areaName })
      this.searchHeaderForm.layoutId = layoutId
      this.$set(this.selectList, 'layoutId', layoutList.data)
      // 3
      const resVal = await eqpAreaApi.eqpLayout({ layoutId: layoutId })
      this.layoutList = resVal.data.eqpInfoList
      this.statusCountList = resVal.data.statusCountList
      this.totalQty = resVal.data.totalQty
      this.getLayoutsInfo()
    },
    // 获取布局详情 绘制布局
    async getEqpLayout(layoutId) {
      const res = await eqpAreaApi.eqpLayout({ layoutId: layoutId })
      this.layoutList = res.data.eqpInfoList
      this.statusCountList = res.data.statusCountList
      this.totalQty = res.data.totalQty
      this.getLayoutsInfo()
    },

    // 有机会重新写 使用iterator 生成器方法写
    foundEqp(keycode) {
      // [...document.getElementsByClassName('equipment')].forEach(item => {
      //   item.style.boxShadow = ''
      // })
      const keys = this.$clearNull(keycode)
      const arr = this.layoutList.filter(ele => {
        // 匹配搜索条件每个item必须包括
        return Object.keys(keys).every(key => {
          // 匹配 layoutList[i] 只要搜索条件有一项包括并且键名相同 并且不区分大小写
          return Object.keys(ele).some(v => new RegExp(keys[key]).test(String(ele[v]).toLowerCase()) && key === v)
        })
      })
      // arr.forEach(item => {
      //   const index = this.layoutList.findIndex(ele => ele.eqp1Id === item.eqp1Id);
      //   [...document.getElementsByClassName('equipment')][index].style.boxShadow = '0 0 10px 10px #F56C6C'
      // })
      const index = this.layoutList.findIndex(ele => ele.eqp1Id === arr[this.count].eqp1Id);
      [...document.getElementsByClassName('equipment')][index].style.boxShadow = '0 0 10px 10px #F56C6C'
      window.scrollTo({
        top: [...document.getElementsByClassName('equipment')][index].offsetTop,
        behavior: 'smooth'
      })
      this.eqpNumbers = {
        allNums: this.layoutList.length,
        checkedEqp: arr.length,
        currentEqp: this.count + 1
      }
      this.count = this.count >= arr.length - 1 ? arr.length - 1 : this.count + 1
    },
    imgFilter(val) {
      const imgItem = {
        'RUN': require('../../../assets/images/device/twodevice_run.png'),
        'ALARM': require('../../../assets/images/device/twodevice_alarm.gif'),
        'IDLE': require('../../../assets/images/device/device_idle.png'),
        'NETWORKFAILURE': require('../../../assets/images/device/twodevice_network.gif'),
        'STOP': require('../../../assets/images/device/twodevice_stop.gif')
      }
      return imgItem[val]
    },
    async changeRouter(name, form) {
      const { eqp1Id } = form
      await this.$refs.ctxshow.hideMenu()
      await this.$router.push({ name, params: { eqp1Id }})
    },
    async workRecordRouter(name, form) {
      const { eqp1Id, testerId, headId, lotId } = form
      await this.$refs.ctxshow.hideMenu()
      await this.$router.push({ name, query: { eqp1Id, testerId, headId, lotId }})
    },
    // 获取类似于背景图片的接口
    async getLayoutsInfo() {
      const layoutInfo = await getLayoutsInfo({ id: this.searchHeaderForm.layoutId })
      this.layoutAttr = layoutInfo.data
    },
    // 获取区域名称
    async getEqpAreasList() {
      const res = await eqpAreaApi.getEqpAreasList()
      this.$set(this.selectList, 'areaName', res.data)
    },
    // 打开弹窗
    layoutInfoForm(id) {
      eqpAreaApi.getBaseInfo({ eqpId: id }).then(res => {
        this.$refs.basicInformationForm.openDialog(res.data)
      })
    },
    show(val) {
      this.eqpInfo = val
    },
    hide() {}
  }
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/defaultStyle.scss";
::v-deep .el-row:nth-child(1) {
  padding-bottom: 0;
}
::v-deep .el-form {
  padding-top: 10px;
  background: #fff;
  // .el-form-item {
  //   margin-bottom: 15px;
  // }
}

.monitor{
  box-sizing: border-box;
  padding-bottom: 60px;
}
.box-eqp {
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    background-color: #fff;
}
.el-row {
  min-height: 46px;
  padding: 10px;
  background-color: #fff;
}
.grid-content{
  display: flex;
  overflow-x: auto;
  overflow-y: hidden;
}
.grid-content-left {
  width: 1200px;
  height: 1000px;
  margin-right: 20px;
  .grid-content-left-c {
    position: relative;
    width: 1200px;
    height: 1000px;
    background-size: 100% 100%;
  }
}
.grid-content-right{
  width: 200px;
}
.equipment {
  position: absolute;
  display: inline-block;
  width: 100px;
  height: 100px;
  box-sizing: border-box;
  padding-top: 5px;
  background-repeat: no-repeat;
  cursor: pointer;
  font-size: 12px;
  font-weight: 700;
  span{
    display: block;
    margin-left: 5px;
  }
  .status-display {
    width: 100px;
    height: 25px;
    text-align: center;
    line-height: 24px;
    font-weight: bold;
    border: 2px solid;
    border-top: 0;
    position: absolute;
    left: 0;
    bottom: -25px;
  }
}
.ctx-menu-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .ctxshow-menu {
    display: block;
    padding: 10px;
    width: 100%;
    font-size: 14px;
  }
  .ctxshow-menu:hover {
    background-color: #428bca;
    color: #fff;
  }
}
</style>
